import { _decorator, Button, Component, Enum, Label, math, ProgressBar, sp, Sprite } from 'cc';
import { tween } from 'cc';
import { UISkill } from '../UISkill';
import GameData, { SkillDefine } from '../../data/GameData';
import { AudioManager } from '../../game/AudioManager';
import Utils from '../../utils/Utils';
const { ccclass, property } = _decorator;

@ccclass('SkillItem')
export class SkillItem extends Component {
    @property(Button) btn_add: Button = null;
    @property(Button) btn_reduce: Button = null;
    @property(Label) level: Label = null;
    @property(ProgressBar) skillProgress: ProgressBar = null;
    @property({ type: Enum(SkillDefine) }) skillDefine: SkillDefine = SkillDefine.Sing;

    private readonly maxValue: number = 4;
    skillLevel: number = 0;

    public onSkillChanged: Function;

    start() {
        Utils.AutoScale(this.btn_add.node, 0.3);
        Utils.AutoScale(this.btn_reduce.node, 0.3);
        this.updateSkillDisplay();
        this.btn_add.node.on(Button.EventType.CLICK, this.onAddClick, this);
        this.btn_reduce.node.on(Button.EventType.CLICK, this.onReduceClick, this);
    }

    onAddClick() {
        AudioManager.Instance.playUIClick();
        if (GameData.skillRemainNum > 0 && this.skillLevel < this.maxValue) {
            GameData.skillRemainNum--;
            this.skillLevel++;
            this.onSkillChanged?.(false);
            this.updateSkillDisplay();
        }
    }

    onReduceClick() {
        AudioManager.Instance.playUIClick();
        if (this.skillLevel > 0) {
            GameData.skillRemainNum++;
            this.skillLevel--;
            this.onSkillChanged?.(false);
            this.updateSkillDisplay();
        }
    }

    private updateSkillDisplay() {
        this.level.string = `${this.skillLevel}`;
        const targetProgress = math.clamp(this.skillLevel / this.maxValue, 0, 1);
        // 使用 tween 平滑过渡进度条
        tween(this.skillProgress)
            .to(0.3, { progress: targetProgress }, { easing: 'quadOut' })
            .start();

        // 按钮状态控制
        this.btn_add.interactable = GameData.skillRemainNum > 0 && this.skillLevel < this.maxValue;
        this.btn_add.getComponentInChildren(Sprite).grayscale = !this.btn_add.interactable;

        this.btn_reduce.interactable = this.skillLevel > 0;
        this.btn_reduce.getComponentInChildren(Sprite).grayscale = !this.btn_reduce.interactable;
    }
}


